package com.cn.jinl.service;


import com.cn.jinl.api.ILoginService;
import com.cn.jinl.api.IOnDutyBgService;
import com.cn.jinl.api.IOnDutyBgTaskService;
import com.cn.jinl.dao.OnDutyBgShenchangMapper;
import com.cn.jinl.dao.OnDutyBgTaskMapper;
import com.cn.jinl.dao.OnDutyBgTaskUserMapper;
import com.cn.jinl.domain.*;
import com.cn.jinl.utils.CommonUtil;
import com.cn.jinl.utils.Constants;
import com.cn.jinl.utils.NumberUtil;
import com.cn.jinl.utils.QueryForm;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class OnDutyBgTaskServiceImpl implements IOnDutyBgTaskService {

    @Autowired
    private OnDutyBgTaskMapper onDutyBgTaskMapper;

    @Autowired
    private OnDutyBgTaskUserMapper onDutyBgTaskUserMapper;

    @Autowired
    private OnDutyBgShenchangMapper onDutyBgShenchangMapper;

    @Autowired
    private IOnDutyBgService onDutyBgService;

    @Autowired
    private ILoginService loginService;

    @Override
    public Map<String, Object> getOnDutyBgTaskList(String bgId, String whiteDay) throws Exception {
        Map<String, Object> resultMap = Maps.newLinkedHashMap();
        resultMap.put("1", Lists.newLinkedList());
        resultMap.put("2", Lists.newLinkedList());
        resultMap.put("3", Lists.newLinkedList());
        resultMap.put("4", Lists.newLinkedList());
        resultMap.put("5", Lists.newLinkedList());
        if (StringUtils.isEmpty(bgId) || StringUtils.isEmpty(whiteDay)) {
            return resultMap;
        }
        OnDutyBgTask paramTask = new OnDutyBgTask();
        paramTask.setWhiteDay(whiteDay);
        paramTask.setBgId(bgId);
        List<OnDutyBgTask> onDutyBgTasks = onDutyBgTaskMapper.selectBgTasksByBgId(paramTask);
        for(OnDutyBgTask onDutyBgTask : onDutyBgTasks){
            String itemName = onDutyBgTask.getItemName();
            if(resultMap.containsKey(itemName)){
                List<OnDutyBgTask> tasks = (List<OnDutyBgTask>) resultMap.get(itemName);
                tasks.add(onDutyBgTask);
                resultMap.put(itemName,tasks);
            }
        }
        OnDutyBgShenchang param = new OnDutyBgShenchang();
        param.setBgId(bgId);
        param.setWhiteDay(whiteDay);
        List<OnDutyBgShenchang> onDutyBgShenchangs = onDutyBgShenchangMapper.selectOndutyShenchangs(param);
        for(OnDutyBgShenchang shenchang:onDutyBgShenchangs){
            String itemType = shenchang.getItemType();
            if(resultMap.containsKey(itemType)){
                List<OnDutyBgShenchang> shenchangs = (List<OnDutyBgShenchang>) resultMap.get(itemType);
                shenchangs.add(shenchang);
                resultMap.put(itemType,shenchangs);
            }
        }
        return resultMap;
    }

    @Override
    public List<OnDutyBgTask> getOnDutyBgTaskListByItemName(QueryForm queryForm) throws Exception {
        List<OnDutyBgTask> onDutyBgTasks = onDutyBgTaskMapper.selectBgTaskByItemName(queryForm);
        return onDutyBgTasks;
    }

    @Override
    public List<OnDutyBgTaskDetailVo> getAllBgTasksByBgId(String bgId) throws Exception {
        List<OnDutyBgShenchang> onDutyBgShenchangs = onDutyBgShenchangMapper.selectOndutyShenchangByBgId(bgId);
        List<OnDutyBgTask> onDutyBgTasks = onDutyBgTaskMapper.selectAllBgTasksByBgId(bgId);
        Map<String,String> roleMaps = loginService.getLoginAndRoleMap();
        Map<String,String> deptMaps = loginService.getLoginAndDeptMap();
        List<OnDutyBgTaskDetailVo> result = Lists.newLinkedList();
        List<String> shengchangUserIds = Lists.newArrayList();
        for(OnDutyBgShenchang onDutyBgShenchang :onDutyBgShenchangs){
            if(shengchangUserIds.contains(onDutyBgShenchang.getUserId())){
                continue;
            }
            OnDutyBgTaskDetailVo vo = new OnDutyBgTaskDetailVo();
            vo.setDeptName(onDutyBgShenchang.getDeptName());
            vo.setRoleName(roleMaps.get(onDutyBgShenchang.getUserId()));
            vo.setUserName(onDutyBgShenchang.getUserName());
            String whiteDayCn = "";
            if(StringUtils.equals(onDutyBgShenchang.getWhiteDay(),"1")){
                whiteDayCn = "白班";
            }else if(StringUtils.equals(onDutyBgShenchang.getWhiteDay(),"2")){
                whiteDayCn = "夜班";
            }
            vo.setWhiteDay(whiteDayCn);
            vo.setKaoQIn(onDutyBgShenchang.getKaoQin());
            result.add(vo);
            shengchangUserIds.add(onDutyBgShenchang.getUserId());
        }
        Map<String,OnDutyBgTaskDetailVo> detailVoMap = Maps.newLinkedHashMap();
        for(OnDutyBgTask bgTask : onDutyBgTasks){
            List<OnDutyBgTaskUser> onDutyBgTaskUsers = bgTask.getOnDutyBgTaskUsers();
            if(CollectionUtils.isEmpty(onDutyBgTaskUsers)){
                continue;
            }
            for(OnDutyBgTaskUser taskUser:onDutyBgTaskUsers){
                String key = taskUser.getUserId()+ "_"+taskUser.getWhiteDay();
                OnDutyBgTaskDetailVo vo = new OnDutyBgTaskDetailVo();
                if(detailVoMap.containsKey(key)){
                     vo = detailVoMap.get(key);
                }
                vo.setDeptName(deptMaps.get(taskUser.getUserId()));
                vo.setRoleName(roleMaps.get(taskUser.getUserId()));
                vo.setUserName(taskUser.getUserName());
                String whiteDayCn = "";
                if(StringUtils.equals(taskUser.getWhiteDay(),"1")){
                    whiteDayCn = "白班";
                }else if(StringUtils.equals(taskUser.getWhiteDay(),"2")){
                    whiteDayCn = "夜班";
                }
                vo.setWhiteDay(whiteDayCn);
                vo.setKaoQIn(taskUser.getKaoQin());
                String xinZi = vo.getXinzi();
                String buQuan = vo.getBuQuan();

                String userPrice = taskUser.getUserPrice();
                String userBuQuan = taskUser.getBuQuan();

                double totalUserPrice = 0.0;
                double totalUserBuQuan = 0.0;
                double totalJiJianXInZi = 0.0;
                if(StringUtils.isNotEmpty(userPrice)){
                    totalUserPrice = Double.parseDouble(userPrice) + Double.parseDouble(xinZi);
                }
                if(StringUtils.isNotEmpty(userBuQuan)){
                    totalUserBuQuan = Double.parseDouble(buQuan) + Double.parseDouble(userBuQuan);
                }
                totalJiJianXInZi = totalUserPrice+totalUserBuQuan;
                vo.setXinzi(NumberUtil.getPoint(totalUserPrice,1));
                vo.setBuQuan(NumberUtil.getPoint(totalUserBuQuan,1));
                vo.setJijianXinZi(NumberUtil.getPoint(totalJiJianXInZi,1));
                detailVoMap.put(key,vo);
            }
        }
        for(String key:detailVoMap.keySet()){
            result.add(detailVoMap.get(key));
        }
        return result;
    }

    @Override
    public OnDutyBgTask getOnDutyBgTaskWithUserListById(String id) throws Exception {
        List<OnDutyBgTask> onDutyBgTasks = onDutyBgTaskMapper.selectBgTaskById(id);
        if(CollectionUtils.isEmpty(onDutyBgTasks)){
            return new OnDutyBgTask();
        }
        return onDutyBgTasks.get(0);
    }

    @Override
    public List<OnDutyBgTaskUser> getOnDutyBgTaskUsersByTaskId(String taskId) throws Exception {
        if(StringUtils.isEmpty(taskId)){
            return Lists.newArrayList();
        }
        OnDutyBgTaskUserExample example = new OnDutyBgTaskUserExample();
        example.createCriteria().andBgTaskIdEqualTo(taskId);
        return onDutyBgTaskUserMapper.selectByExample(example);
    }

    @Override
    public OnDutyBgTask getOnDutyBgTaskListById(String id) throws Exception {
        OnDutyBgTaskExample example = new OnDutyBgTaskExample();
        example.createCriteria().andIdEqualTo(id).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<OnDutyBgTask> tasks = onDutyBgTaskMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(tasks)){
            return null;
        }
        return tasks.get(0);
    }

    @Override
    public String batchInsertOnDutyBgTasks(List<OnDutyBgTask> onDutyBgTasks) throws Exception {
        return null;
    }

    @Override
    public String batchUpdateOnDutyBgTasks(OnDutyBgTaskVo onDutyBgTasksVo) throws Exception {
        List<OnDutyBgTask> onDutyBgTasks = onDutyBgTasksVo.getOnDutyBgTasks();
        if(CollectionUtils.isEmpty(onDutyBgTasks)){
            return "数据不能为空！";
        }
        String bgId = onDutyBgTasksVo.getBgId();
        String whiteDay = onDutyBgTasksVo.getWhiteDay();
        String dutyDay = onDutyBgTasksVo.getDutyDay();
        String applyUser = onDutyBgTasksVo.getApplyName();
        OnDutyBg onDutyBg = onDutyBgService.getOnDutyBgById(bgId);
        if(null == onDutyBg){
            return "报工记录不存在！";
        }
        if(StringUtils.equals(onDutyBg.getBgStatus(),"1")){
            return "记录已经审核，不能再次编辑！";
        }
        OnDutyBgTaskExample example = new OnDutyBgTaskExample();
        example.createCriteria().andBgIdEqualTo(bgId).andWhiteDayEqualTo(whiteDay);
        int count = onDutyBgTaskMapper.deleteByExample(example);
        if(count < 0){
            return "清理报工记录异常！";
        }
        OnDutyBgTaskUserExample userExample = new OnDutyBgTaskUserExample();
        userExample.createCriteria().andWhiteDayEqualTo(whiteDay).andDutyDayEqualTo(dutyDay);
        count = onDutyBgTaskUserMapper.deleteByExample(userExample);
        if(count < 0){
            return "清理报工记录异常1！";
        }

        OnDutyBgShenchang param = new OnDutyBgShenchang();
        param.setBgId(bgId);
        param.setWhiteDay(whiteDay);
        //清理非生产数据
        if(StringUtils.equals("1",onDutyBgTasksVo.getNotProduct())){
            param.setItemType("5");
        }
        count = onDutyBgShenchangMapper.deleteDutyShengchangByBgId(param);
        if(count < 0){
            return "清理报工记录异常11！";
        }

        List<OnDutyBgTaskUser> allAddTaskUsers = Lists.newArrayList();
        Set<String> whiteUsers = Sets.newHashSet();
        Set<String> blackUsers = Sets.newHashSet();
        Set<String> buqunUsers = Sets.newHashSet();
        for(OnDutyBgTask onDutyBgTask : onDutyBgTasks){
            String id = CommonUtil.generateRandomNum("onDutyBgTask-");
            onDutyBgTask.setId(id);
            onDutyBgTask.setBgId(bgId);
            onDutyBgTask.setWhiteDay(whiteDay);
            onDutyBgTask.setDutyDay(dutyDay);
            List<OnDutyBgTaskUser> onDutyBgTaskUsers = onDutyBgTask.getOnDutyBgTaskUsers();
            if(!CollectionUtils.isEmpty(onDutyBgTaskUsers)){
                for(OnDutyBgTaskUser user : onDutyBgTaskUsers){
                    user.setBgTaskId(id);
                    user.setWhiteDay(whiteDay);
                    user.setDutyDay(dutyDay);
                    if(StringUtils.equals("1",whiteDay)){
                        whiteUsers.add(user.getUserId());
                    }else{
                        blackUsers.add(user.getUserId());
                    }
                    if(StringUtils.isNotEmpty(user.getBuQuan())){
                        buqunUsers.add(user.getUserId());
                    }
                }
                allAddTaskUsers.addAll(onDutyBgTaskUsers);
            }
        }

        Set<String> notShengchangUsers = Sets.newHashSet();
        List<OnDutyBgShenchang> onDutyBgShenchangs = onDutyBgTasksVo.getOnDutyBgShenchangs();
        for(OnDutyBgShenchang sc : onDutyBgShenchangs){
            if(StringUtils.equals("1",whiteDay)){
                whiteUsers.add(sc.getUserId());
            }else{
                blackUsers.add(sc.getUserId());
            }
            sc.setWhiteDay(whiteDay);
            sc.setDutyDay(dutyDay);
            sc.setBgId(bgId);
            if(StringUtils.equals(sc.getItemType(),"5")){
                notShengchangUsers.add(sc.getUserId());
                sc.setWhiteDay("");
            }
        }

        String reverseWhiteDay = StringUtils.equals(whiteDay,"1")?"2":"1";
        userExample = new OnDutyBgTaskUserExample();
        userExample.createCriteria().andWhiteDayEqualTo(reverseWhiteDay).andDutyDayEqualTo(dutyDay);
        List<OnDutyBgTaskUser> existUsers = onDutyBgTaskUserMapper.selectByExample(userExample);
        if(!CollectionUtils.isEmpty(existUsers)){
            for(OnDutyBgTaskUser user : existUsers){
                if(StringUtils.equals("1",reverseWhiteDay)){
                    whiteUsers.add(user.getUserId());
                }else{
                    blackUsers.add(user.getUserId());
                }
                if(StringUtils.isNotEmpty(user.getBuQuan())){
                    buqunUsers.add(user.getUserId());
                }
            }
        }

        OnDutyBgShenchangExample shenchangExample = new OnDutyBgShenchangExample();
        shenchangExample.createCriteria().andBgIdEqualTo(bgId).andDutyDayEqualTo(reverseWhiteDay);
        List<OnDutyBgShenchang> existShengchangs = onDutyBgShenchangMapper.selectByExample(shenchangExample);
        if(!CollectionUtils.isEmpty(existShengchangs)){
            for(OnDutyBgShenchang sc : existShengchangs){
                if(StringUtils.equals("1",reverseWhiteDay)){
                    whiteUsers.add(sc.getUserId());
                }else{
                    blackUsers.add(sc.getUserId());
                }
            }
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String nowDay = simpleDateFormat.format(new Date());
        if(StringUtils.equals("1",whiteDay)){
            onDutyBg.setWhiteSaveTime(nowDay);
            if(StringUtils.isEmpty(onDutyBg.getWhiteApplyTime())){
                onDutyBg.setWhiteApplyTime(nowDay);
            }
            onDutyBg.setWhiteUserCount(whiteUsers.size()+"");
            onDutyBg.setWhiteApplyUser(applyUser);
        }else{
            onDutyBg.setBlackSaveTime(nowDay);
            if(StringUtils.isEmpty(onDutyBg.getBlackApplyTime())){
                onDutyBg.setBlackApplyTime(nowDay);
            }
            onDutyBg.setBlackUserCount(+blackUsers.size()+"");
            onDutyBg.setBlackApplyUser(applyUser);
        }
        onDutyBg.setTotalUserCount((whiteUsers.size()+blackUsers.size())+"");
        onDutyBg.setSaves("1");
        if(StringUtils.equals(onDutyBgTasksVo.getBgStatus(),"1")){
            onDutyBg.setBgStatus("1");
            onDutyBg.setCheckUserId(onDutyBgTasksVo.getCheckUserId());
            onDutyBg.setCheckUserName(onDutyBgTasksVo.getCheckUserName());
            onDutyBg.setCheckTime(nowDay);
        }
        onDutyBg.setBuQuanUserCount(buqunUsers.size()+"");
        onDutyBg.setChuqinTotalUser(notShengchangUsers.size()+"");
        String resp = onDutyBgService.updateOnDutyBg(onDutyBg);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        if(!CollectionUtils.isEmpty(onDutyBgShenchangs)){
            if(!StringUtils.equals("1",onDutyBgTasksVo.getNotProduct())){
                Iterator<OnDutyBgShenchang> iterator = onDutyBgShenchangs.iterator();
                while(iterator.hasNext()){
                    OnDutyBgShenchang shenchang = iterator.next();
                    if(StringUtils.equals(shenchang.getItemType(),"5")){
                        iterator.remove();
                    }
                }
            }
            count = onDutyBgShenchangMapper.batchInsertDutyShengchangs(onDutyBgShenchangs);
            if(count < 0){
                throw new Exception("批量插入生产表异常");
            }
        }
        if(!CollectionUtils.isEmpty(onDutyBgTasks)){
            count = onDutyBgTaskMapper.batchInsertDutyTask(onDutyBgTasks);
            if(count < 0){
                throw new Exception("批量插入产量表异常");
            }
        }
        if(!CollectionUtils.isEmpty(allAddTaskUsers)){
            count = onDutyBgTaskUserMapper.batchInsertTaskUsers(allAddTaskUsers);
            if(count < 0){
                throw new Exception("批量插入产量表用户异常");
            }
        }
        return "";
    }
}
